package com.epalmpay.service.prepurchase.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.epalmpay.bean.PreTradeBean;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.prepurchase.DoAddPrePurchBalanceInDTO;
import com.epalmpay.dto.prepurchase.PreBalanceChangeInDTO;
import com.epalmpay.dto.prepurchase.PreBalanceChangeListOutDTO;
import com.epalmpay.dto.prepurchase.PreBalanceChangeOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityInfoOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityListOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityMoreInfoOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityStaticListOutDTO;
import com.epalmpay.dto.prepurchase.PrePurActivityStaticOutDTO;
import com.epalmpay.dto.prepurchase.PrePurApproveInDTO;
import com.epalmpay.dto.prepurchase.PrePurInDTO;
import com.epalmpay.dto.prepurchase.PreTradeOutDTO;
import com.epalmpay.dto.prepurchase.PrepurchaseInfoInDTO;
import com.epalmpay.dto.prepurchase.ReceiceInfoInDTO;
import com.epalmpay.dto.prepurchase.ReceiceInfoListOutDTO;
import com.epalmpay.dto.prepurchase.ReceiceInfoOutDTO;
import com.epalmpay.dto.prepurchase.ShopPrePurListOutDTO;
import com.epalmpay.dto.prepurchase.UpdateInPrepurInDTO;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.entity.Agent;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.GroupReceiveInfo;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.PrePurchaseActivity;
import com.epalmpay.entity.PrePurchaseMoneyChange;
import com.epalmpay.entity.PrepurchaseActivityStatis;
import com.epalmpay.entity.Shop;
import com.epalmpay.entity.ShopGroupRelation;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.entity.Userbase;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.BizEnum.PrePurchaseActivityStatus;
import com.epalmpay.mapper.AgentMapper;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.GroupReceiveInfoMapper;
import com.epalmpay.mapper.PrePurchaseActivityMapper;
import com.epalmpay.mapper.PrePurchaseMoneyChangeMapper;
import com.epalmpay.mapper.PrepurchaseActivityStatisMapper;
import com.epalmpay.mapper.ProfitMapper;
import com.epalmpay.mapper.ShopGroupRelationMapper;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.mapper.YsShopCarMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayBalanceChange;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.prepurchase.IPrePurchaseService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.payplat.UtilFun;
@Service
public class PrePurchaseServiceImpl implements IPrePurchaseService{

	@Autowired
	private GroupReceiveInfoMapper groupReceiveInfoMapper;
	
	@Autowired
	private PrePurchaseActivityMapper prePurchaseActivityMapper;
	
	@Autowired
	private AgentMapper agentMapper;
	
	@Autowired
	private YsShopCarMapper ysShopCarMapper;
	
	
	@Resource
	private PrePurchaseMoneyChangeMapper prePurchaseMoneyChangeMapper;
	@Resource
	private  UserbaseMapper userbaseMapper;
	
	@Resource
	private  GroupMapper groupMapper ;
	
	@Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	
	@Resource
	private  PrepurchaseActivityStatisMapper prepurchaseActivityStatisMapper;
	
	@Resource
	private TradeOfflineMapper  tradeOfflineMapper;
	
	@Resource
	private ShopMapper  shopMapper;
	
	
	
	@Resource
	private ProfitMapper profitMapper;
	@Override
	public BaseOutDTO addReceiceInfo(ReceiceInfoInDTO receiceInfoInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		GroupReceiveInfo temp=groupReceiveInfoMapper.selectReceiceInfo(receiceInfoInDTO.getGroupId(),receiceInfoInDTO.getMerchantCode());
		if(temp!=null){
			baseOutDTO.setErrorCode("0032", "此商户号已经存在");
			return baseOutDTO;
		}
		GroupReceiveInfo groupReiveInfo=new GroupReceiveInfo();
		groupReiveInfo.setChannelFlag(receiceInfoInDTO.getChannelFlag());
		groupReiveInfo.setGmtCreate(new Date());
		groupReiveInfo.setGmtModified(new Date());
		groupReiveInfo.setGroupId(receiceInfoInDTO.getGroupId());
		groupReiveInfo.setMemo(receiceInfoInDTO.getMemo());
		groupReiveInfo.setMerchantCode(receiceInfoInDTO.getMerchantCode().trim());
		groupReiveInfo.setMerchantName(receiceInfoInDTO.getMerchantName());
		groupReiveInfo.setStatus(receiceInfoInDTO.getStatus());
		groupReiveInfo.setTerminalCode(receiceInfoInDTO.getTerminalCode());
		groupReiveInfo.setTradeAmountPerMonth(0L);
		groupReiveInfo.setUpdateUser(receiceInfoInDTO.getUpdateUser());
		groupReiveInfo.setUpdateUserId(receiceInfoInDTO.getUpdateUserId());
		int result= groupReceiveInfoMapper.insert(groupReiveInfo);
		if(result>0){
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
			return baseOutDTO;
		}else{
			baseOutDTO.setErrorCode("0033", "此数据库操作失败");
			return baseOutDTO;
		}
	}

	@Override
	public Boolean deleteReceiceInfo(ReceiceInfoInDTO receiceInfoInDTO) throws ApplicationException {
		
		GroupReceiveInfo groupReiveInfo=groupReceiveInfoMapper.selectByPrimaryKey(receiceInfoInDTO.getId());
		if(groupReiveInfo.getGroupId().equals(receiceInfoInDTO.getGroupId())){
			groupReiveInfo.setStatus(0);
			groupReiveInfo.setUpdateUser(receiceInfoInDTO.getUpdateUser());
			groupReiveInfo.setUpdateUserId(receiceInfoInDTO.getUpdateUserId());
			groupReiveInfo.setGmtModified(new Date());
		   int result= groupReceiveInfoMapper.updateByPrimaryKey(groupReiveInfo);
		   return result>0;
		}else{
		   throw new ApplicationException("您无权操作该记录");	
		}
	}

	@Override
	public ReceiceInfoOutDTO findReceiceInfo(ReceiceInfoInDTO receiceInfoInDTO) throws ApplicationException {
		ReceiceInfoOutDTO receiceInfoOutDTO=new ReceiceInfoOutDTO();
		GroupReceiveInfo groupReceiveInfo=groupReceiveInfoMapper.selectByPrimaryKey(receiceInfoInDTO.getId());
		if(groupReceiveInfo!=null){
			try {
				PropertyCopyUtil.copyPPropertiesNotNull(groupReceiveInfo, receiceInfoOutDTO);
				receiceInfoOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			receiceInfoOutDTO.setErrorCode("00X0", "订单不存在");
		}
		return receiceInfoOutDTO;
	}
	
	@Override
	public ReceiceInfoListOutDTO listReceiceInfo(ReceiceInfoInDTO receiceInfoInDTO, Page page) throws ApplicationException {
		ReceiceInfoListOutDTO receiceInfoOutDTO = new ReceiceInfoListOutDTO();
		receiceInfoOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("channelFlag",receiceInfoInDTO.getChannelFlag());
		param.put("merchantCode",receiceInfoInDTO.getMerchantCode());
		param.put("groupId",receiceInfoInDTO.getGroupId());
		int sumCount = groupReceiveInfoMapper.queryReceiceInfoCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return receiceInfoOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<ReceiceInfoOutDTO> oilcardOutDTOList = groupReceiveInfoMapper.queryReceiceInfoList(param);
		receiceInfoOutDTO.setReceiceInfoList(oilcardOutDTOList);
		return receiceInfoOutDTO;
	}

	@Override
	public BaseOutDTO addPrePurchaseActivity(PrepurchaseInfoInDTO  prePurInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		Agent agent=agentMapper.selectByPrimaryKey(prePurInDTO.getAgentId());
		ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(prePurInDTO.getGroupId(), prePurInDTO.getShopId());
		if(agent==null||shopGroupRelation==null||!agent.getGroupId().equals(prePurInDTO.getGroupId())){
			baseOutDTO.setErrorCode("0032", "参数信息错误");
			return baseOutDTO;
		}
	   String startDate=prePurInDTO.getStartDate();
		PrePurchaseActivity temp=prePurchaseActivityMapper.findPrePurchaseActivity(prePurInDTO.getShopId(),prePurInDTO.getGroupId(),startDate);	
		if(temp!=null){
			baseOutDTO.setErrorCode("0032", "此商户此段时间已存在采购活动");
			return baseOutDTO;
		}
		
		
		//将这个代理商的余额减掉
		if(agent.getPrePurchaseStatus()==null||agent.getPrePurchaseStatus().intValue()!=1){
			baseOutDTO.setErrorCode("0033", "当前代理商无权创建预采购计划");
			return baseOutDTO;
		}
		
		
		if(agent.getPrePurchaseBalance()==null||agent.getPrePurchaseBalance().intValue()<prePurInDTO.getPrepurchaseAmount()*100){
			baseOutDTO.setErrorCode("0033", "当前代理商预采购余额不足");
			return baseOutDTO;
		}	
		
		String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
			throw new ApplicationException("代理商的预采购余额信息不正常，请联系客服");
		}
   
	   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
		if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
			throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
		}
		
		PrePurchaseActivity prPurchaseActivity=new PrePurchaseActivity();
		
		prPurchaseActivity.setAgentBenefitAmount(prePurInDTO.getAgentBenefitAmount());
		prPurchaseActivity.setAgentId(prePurInDTO.getAgentId());
		
		
		prPurchaseActivity.setCreateUserId(agent.getUserId());
		prPurchaseActivity.setCustomerBenefitAmount(prePurInDTO.getCustomerBenefitAmount());
		prPurchaseActivity.setStartDate(SysUtils.parseDate(prePurInDTO.getStartDate(),"yyyy-MM-dd"));
		prPurchaseActivity.setGroupId(prePurInDTO.getGroupId());
		prPurchaseActivity.setMerchantPresetAmount(prePurInDTO.getMerchantPresetAmount()*100);
		prPurchaseActivity.setPrepurchaseAmount(prePurInDTO.getPrepurchaseAmount()*100);
		prPurchaseActivity.setPrepurchaseType(prePurInDTO.getPrepurchaseType());
		prPurchaseActivity.setAgentBenefitAmount(prePurInDTO.getAgentBenefitAmount());
		prPurchaseActivity.setCustomerBenefitAmountNew(prePurInDTO.getCustomerBenefitAmount());
		prPurchaseActivity.setShopId(prePurInDTO.getShopId());
		prPurchaseActivity.setLastTradeDate(new Date());
		prPurchaseActivity.setMerchantLastDayAmount(0);
		prPurchaseActivity.setMerchantTodayAmount(0);
		prPurchaseActivity.setRiskAmount(0l);
		prPurchaseActivity.setCustomerSaleAmount(0l);
		prPurchaseActivity.setMerchantSettedAmount(0L);
		prPurchaseActivity.setCustomerPayAmount(0L);
		prPurchaseActivity.setCustomerSaleCount(0);
		prPurchaseActivity.setGmtModified(new Date());
		prPurchaseActivity.setGmtCreate(new Date());
		if(StringUtils.isNotBlank(prePurInDTO.getEndDate())){
			prPurchaseActivity.setEndDate(SysUtils.parseDate(prePurInDTO.getEndDate(),"yyyy-MM-dd"));
		}
		if(prPurchaseActivity.getMerchantPresetAmount()>0){
			prPurchaseActivity.setStatus(PrePurchaseActivityStatus.create.getType());			
		}else{
			prPurchaseActivity.setApproveInfo("预结算金额为0，无需审核");
			prPurchaseActivity.setApproveUserId(agent.getUserId());
			prPurchaseActivity.setStatus(PrePurchaseActivityStatus.approveSuccess.getType());
		}
		
		int result= prePurchaseActivityMapper.insert(prPurchaseActivity);
		
		//
		long amount=prPurchaseActivity.getAgentBenefitAmount()*prPurchaseActivity.getPrepurchaseAmount()/100;
        PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
        prePurchaseMoneyChange.setAgentId(agent.getId());
        prePurchaseMoneyChange.setAmount(amount);
        prePurchaseMoneyChange.setChangeType(0);
        prePurchaseMoneyChange.setGmtCreate(new Date());
        prePurchaseMoneyChange.setGmtModified(new Date());
        prePurchaseMoneyChange.setGroupId(prePurInDTO.getGroupId());
        String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
        String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
        prePurchaseMoneyChange.setInfoDesc("代理商商创建预采购活动，扣除可用余额"+";调整前余额为"+balanceStr+",调整前额度为"+moneyStr
        		+",调整金额为" +SysUtils.formatNumber(amount/100,2));
        
        //
        
      
        
        prePurchaseMoneyChange.setOperateUser(prePurInDTO.getUpdateUser());
        prePurchaseMoneyChange.setOperateUserId(prePurInDTO.getUpdateUserId());
        prePurchaseMoneyChange.setType(2);//表示代理商创建活动，余额变更
        
        int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())-Long.valueOf(amount).intValue();
      	 agent.setPrePurchaseBalance(balance);  
      	 String descMoney2=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
      	 agent.setPrePurchaseBalanceDes(descMoney2);
      	 
      	
         prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
         
         agentMapper.updateByPrimaryKey(agent);
		
		if(result>0){
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
			return baseOutDTO;
		}else{
			baseOutDTO.setErrorCode("0033", "此数据库操作失败");
			return baseOutDTO;
		}
	
	}
	
	@Override
	public BaseOutDTO doEditPrePurActivity(PrepurchaseInfoInDTO prePurInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		Agent agent=agentMapper.selectByPrimaryKey(prePurInDTO.getAgentId());
		ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(prePurInDTO.getGroupId(), prePurInDTO.getShopId());
		if(agent==null||shopGroupRelation==null||!agent.getGroupId().equals(prePurInDTO.getGroupId())){
			baseOutDTO.setErrorCode("0032", "参数信息错误");
			return baseOutDTO;
		}
	    String startDate=prePurInDTO.getStartDate();
		PrePurchaseActivity prPurchaseActivity=prePurchaseActivityMapper.findPrePurchaseActivity(prePurInDTO.getShopId(),prePurInDTO.getGroupId(),startDate);
		
		if(prPurchaseActivity!=null && !prPurchaseActivity.getId().equals(prePurInDTO.getId())){
			baseOutDTO.setErrorCode("0032", "此商户此段时间已存在采购活动");
			return baseOutDTO;
		}
		
		
		//将这个代理商的余额减掉
		if(agent.getPrePurchaseStatus().intValue()!=1){
			baseOutDTO.setErrorCode("0033", "当前代理商无权创建预采购计划");
			return baseOutDTO;
		}
		
		long amount=prPurchaseActivity.getAgentBenefitAmount()*prPurchaseActivity.getPrepurchaseAmount()/100;
	      //客户端输入的是单位 元
		long amount2=prePurInDTO.getAgentBenefitAmount()*prePurInDTO.getPrepurchaseAmount();
		  
		long changeAmount=amount2-amount;
		if(changeAmount>0){
			if(agent.getPrePurchaseBalance()==null||agent.getPrePurchaseBalance().intValue()<changeAmount){
				baseOutDTO.setErrorCode("0033", "当前代理商预采购余额不足");
				return baseOutDTO;
			}	
		}
		
		
		String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
			throw new ApplicationException("代理商的预采购余额信息不正常，请联系客服");
		}
   
	   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
		if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
			throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
		}
		
		
		
		prPurchaseActivity.setAgentBenefitAmount(prePurInDTO.getAgentBenefitAmount());
		prPurchaseActivity.setAgentId(prePurInDTO.getAgentId());
		
		
		prPurchaseActivity.setCreateUserId(agent.getUserId());
		prPurchaseActivity.setCustomerBenefitAmount(prePurInDTO.getCustomerBenefitAmount());
		prPurchaseActivity.setStartDate(SysUtils.parseDate(prePurInDTO.getStartDate(),"yyyy-MM-dd"));
		prPurchaseActivity.setGroupId(prePurInDTO.getGroupId());
		prPurchaseActivity.setMerchantPresetAmount(prePurInDTO.getMerchantPresetAmount()*100);
		prPurchaseActivity.setPrepurchaseAmount(prePurInDTO.getPrepurchaseAmount()*100);
		prPurchaseActivity.setPrepurchaseType(prePurInDTO.getPrepurchaseType());
		prPurchaseActivity.setAgentBenefitAmount(prePurInDTO.getAgentBenefitAmount());
		prPurchaseActivity.setShopId(prePurInDTO.getShopId());
		if(StringUtils.isNotBlank(prePurInDTO.getEndDate())){
			prPurchaseActivity.setEndDate(SysUtils.parseDate(prePurInDTO.getEndDate(),"yyyy-MM-dd"));
		}
		if(prPurchaseActivity.getMerchantPresetAmount()>0){
			prPurchaseActivity.setStatus(PrePurchaseActivityStatus.create.getType());			
		}else{
			prPurchaseActivity.setApproveInfo("预结算金额为0，无需审核");
			prPurchaseActivity.setApproveUserId(agent.getUserId());
			prPurchaseActivity.setStatus(PrePurchaseActivityStatus.approveSuccess.getType());
		}
		
		int result= prePurchaseActivityMapper.updateByPrimaryKey(prPurchaseActivity);
		
		//
		if(changeAmount!=0){
			PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
	        prePurchaseMoneyChange.setAgentId(agent.getId());
	        prePurchaseMoneyChange.setAmount(changeAmount);
	        prePurchaseMoneyChange.setChangeType(changeAmount>0?0:1);
	        prePurchaseMoneyChange.setGmtCreate(new Date());
	        prePurchaseMoneyChange.setGmtModified(new Date());
	        prePurchaseMoneyChange.setGroupId(prePurInDTO.getGroupId());
	        String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
	        String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
	        prePurchaseMoneyChange.setInfoDesc("代理商商修改预采购活动，调整可用余额"+";调整前余额为"+balanceStr+",调整前额度为"+moneyStr+",调整金额为" +SysUtils.formatNumber(changeAmount/100,2));
	        
	        //
	        
	        prePurchaseMoneyChange.setOperateUser(prePurInDTO.getUpdateUser());
	        prePurchaseMoneyChange.setOperateUserId(prePurInDTO.getUpdateUserId());
	        prePurchaseMoneyChange.setType(3);//表示代理商创建活动，余额变更
	        
	        long balance = SysUtils.Object2int(agent.getPrePurchaseBalance())-changeAmount;
	      	 agent.setPrePurchaseBalance(Long.valueOf(balance).intValue());  
	      	 String descMoney2=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
	      	 agent.setPrePurchaseBalanceDes(descMoney2);
	      	 
	      	
	         prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
	         
	         agentMapper.updateByPrimaryKey(agent);
		}
        
		
		if(result>0){
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
			return baseOutDTO;
		}else{
			baseOutDTO.setErrorCode("0033", "此数据库操作失败");
			return baseOutDTO;
		}
	}


	@Override
	public PrePurActivityListOutDTO listPrePurActivity(PrePurInDTO prePurInDTO, Page page) throws ApplicationException {
		PrePurActivityListOutDTO prePurActivityListOutDTO = new PrePurActivityListOutDTO();
		prePurActivityListOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("agentId",prePurInDTO.getAgentId());
		if(prePurInDTO.getAgentId()!=null){
			  List<Agent>agents=agentMapper.getAllSubAgentByAgentId(prePurInDTO.getAgentId(),prePurInDTO.getGroupId());
			 StringBuffer buffer=new StringBuffer(""+prePurInDTO.getAgentId());
			 if(agents.size()>0 ){
				 for(Agent agent:agents){
					 buffer.append(",").append(agent.getId());
				 }
				 param.put("agentIds",prePurInDTO.getAgentId());
			 }
		  }
		param.put("shopId",prePurInDTO.getShopId());
		param.put("groupId",prePurInDTO.getGroupId());
		
		param.put("joinStart",prePurInDTO.getJoinStart());
		param.put("joinEnd",prePurInDTO.getJoinEnd());
		if(prePurInDTO.getStatus()==null){
			param.put("status","-1");
		}else{
			param.put("status",prePurInDTO.getStatus());
		}
		
		param.put("shopName",prePurInDTO.getShopName());
		param.put("agentName",prePurInDTO.getAgentName());
		int sumCount = prePurchaseActivityMapper.queryPrePurActivityCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return prePurActivityListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PrePurActivityOutDTO> prePurActivityOutDTOs = prePurchaseActivityMapper.queryPrePurActivityList(param);
		prePurActivityListOutDTO.setPrePurActivitys(prePurActivityOutDTOs);
		return prePurActivityListOutDTO;
	}

	@Override
	public Boolean deletePrePurActivity(PrePurInDTO prePurInDTO) throws ApplicationException {

		PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.selectByPrimaryKey(prePurInDTO.getId());
		if(prePurchaseActivity.getGroupId().equals(prePurInDTO.getGroupId())){
			if(prePurchaseActivity.getStatus().intValue()==PrePurchaseActivityStatus.create.getType()
					||prePurchaseActivity.getStatus().intValue()==PrePurchaseActivityStatus.approveFail.getType()){
				Agent agent=agentMapper.selectByPrimaryKey(prePurchaseActivity.getAgentId());
				
				String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
				if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
					throw new ApplicationException("代理商的余额信息不正常，请联系客服");
				}
		   
			   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
				if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
					throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
				}
				long amount=prePurchaseActivity.getAgentBenefitAmount()*prePurchaseActivity.getPrepurchaseAmount()/100;
			    	   PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
				        prePurchaseMoneyChange.setAgentId(agent.getId());
				        prePurchaseMoneyChange.setAmount(amount);
				        prePurchaseMoneyChange.setChangeType(1);
				        prePurchaseMoneyChange.setGmtCreate(new Date());
				        prePurchaseMoneyChange.setGmtModified(new Date());
				        prePurchaseMoneyChange.setGroupId(prePurchaseActivity.getGroupId());
				        String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
				        String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
				        prePurchaseMoneyChange.setInfoDesc("取消创建采购活动，还原创建时减入金额到可用余额"+";调整前余额为"+balanceStr+",额度为"+moneyStr
				        		+",调整金额为" +SysUtils.formatNumber(amount/100,2));
				        
				        //
				        
				        prePurchaseMoneyChange.setOperateUser(prePurInDTO.getUpdateUser());
				        prePurchaseMoneyChange.setOperateUserId(prePurInDTO.getUpdateUserId());
				        
				        prePurchaseMoneyChange.setType(4);//代理商删除活动
				        
				        int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())+Long.valueOf(amount).intValue();
				      	 agent.setPrePurchaseBalance(balance);  
				      	 String descMoney2=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
				      	 agent.setPrePurchaseBalanceDes(descMoney2);
				      	 	 
				         prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
				         
				         agentMapper.updateByPrimaryKey(agent);
			       
				
				prePurchaseActivityMapper.deleteByPrimaryKey(prePurInDTO.getId());
				
				//
			}
		}else{
		   throw new ApplicationException("您无权操作该记录");	
		}
		return true;
	}

	@Override
	public Boolean finishPrePurApprove(PrePurApproveInDTO prePurApproveInDTO) throws ApplicationException {
		//审核失败
		PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.selectByPrimaryKey(prePurApproveInDTO.getId());
		if(prePurchaseActivity==null||!prePurchaseActivity.getGroupId().equals(prePurApproveInDTO.getGroupId())){
			 throw new ApplicationException("参数信息错误");	
		}
		
		Agent agent=agentMapper.selectByPrimaryKey(prePurchaseActivity.getAgentId());
		
		String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		System.out.println("finishPrePurApprove..."+descBalance);
		if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
			throw new ApplicationException("代理商的余额信息不正常，请联系客服");
		}
   
	   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
		if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
			throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
		}
		
		Integer status=prePurApproveInDTO.getStatus();
		if(status.intValue()==1){
			//审核成功，与体现金额
			prePurchaseActivity.setStatus(PrePurchaseActivityStatus.approveSuccess.getType());
			//给商户添加余额
			int tradeAmount=prePurchaseActivity.getMerchantPresetAmount().intValue();
			if(tradeAmount>0){
				  //支付平台请求对象创建
				String orderNum= UtilFun.createOrderNum();
				ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(prePurchaseActivity.getGroupId(),prePurchaseActivity.getShopId());
			    Group  group=groupMapper.selectByPrimaryKey(prePurchaseActivity.getGroupId());
				PayBalanceChange   payBalanceChange = PayBalanceChange.initialize(group.getPayGroupCode(),shopGroupRelation.getPayMerchantCode(),tradeAmount+"" ,
	                    "1",orderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");

				 PayResult payResult = IPayAPI.consumptionBalanceChangeMerchant(payBalanceChange);
                 if(!payResult.getRespCode().equals("0000")) {
                	 throw new ApplicationException("审核失败，商户余额变更错误");
                 }else{
                	 //交易记录创建
                	 TradeOffline  tradeOffline = new TradeOffline();
                     tradeOffline.setGmtCreate(new Date());
                     tradeOffline.setGroupId(prePurchaseActivity.getGroupId());
                     tradeOffline.setOrderId(orderNum);
                     tradeOffline.setReceiverId(prePurchaseActivity.getShopId()+"");
                     tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
                     tradeOffline.setTransactionType((byte) BizEnum.TransactionType.AddBalanceMerchant.getType());
                     tradeOffline.setOrderAmount(tradeAmount);
                     tradeOffline.setRealAmount(tradeAmount);
                     tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
                     tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                     tradeOffline.setTransOrderNo(payBalanceChange.getOrgOrderNum());
                     tradeOffline.setMemo("代理商创建预采购活动，将预提现金额加入商家的余额");
                     tradeOfflineMapper.insertSelective(tradeOffline);
                 }
                 prePurchaseActivity.setMerchantSettedAmount(prePurchaseActivity.getMerchantPresetAmount());
                 prePurchaseActivity.setRiskAmount(prePurchaseActivity.getMerchantPresetAmount()*-1);
			}
			
		}else{
			///审核失败
			prePurchaseActivity.setStatus(PrePurchaseActivityStatus.approveFail.getType());

			long amount=prePurchaseActivity.getAgentBenefitAmount()*prePurchaseActivity.getPrepurchaseAmount()/100;
	    	   PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
		        prePurchaseMoneyChange.setAgentId(agent.getId());
		        prePurchaseMoneyChange.setAmount(amount);
		        prePurchaseMoneyChange.setChangeType(1);
		        prePurchaseMoneyChange.setGmtCreate(new Date());
		        prePurchaseMoneyChange.setGmtModified(new Date());
		        prePurchaseMoneyChange.setGroupId(prePurchaseActivity.getGroupId());
		        String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
		        String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
		        prePurchaseMoneyChange.setInfoDesc("渠道审核失败，还原创建时减入金额到可用余额"+";调整前余额为"+balanceStr+",额度为"+moneyStr
		        		+",调整金额为" +SysUtils.formatNumber(amount/100,2));		       
		        
		        //
		        prePurchaseMoneyChange.setOperateUser(prePurApproveInDTO.getUpdateUser());
		        prePurchaseMoneyChange.setOperateUserId(prePurApproveInDTO.getUpdateUserId());
		        prePurchaseMoneyChange.setType(5);//表示渠道审核失败
		        
		        int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())+Long.valueOf(amount).intValue();
		      	 agent.setPrePurchaseBalance(balance);  
		      	 String descMoney2=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		      	 agent.setPrePurchaseBalanceDes(descMoney2);
		      	 	 
		         prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
		         
		         agentMapper.updateByPrimaryKey(agent);
	       
		}
		
		prePurchaseActivity.setApproveInfo(prePurApproveInDTO.getApproveInfo());
		prePurchaseActivity.setApproveUserId(prePurApproveInDTO.getUpdateUserId());
		prePurchaseActivity.setGmtModified(new Date());
		prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
		return true;
	}

	@Override
	public PreBalanceChangeListOutDTO listPreBalanceChange(PreBalanceChangeInDTO preBalanceChangeInDTO,Page page) throws ApplicationException {
		PreBalanceChangeListOutDTO preBalanceChangeListOutDTO = new PreBalanceChangeListOutDTO();
		preBalanceChangeListOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("agentId",preBalanceChangeInDTO.getAgentId());	
		param.put("groupId",preBalanceChangeInDTO.getGroupId());
		param.put("type",preBalanceChangeInDTO.getType());
		param.put("joinStart",preBalanceChangeInDTO.getJoinStart());
		param.put("joinEnd",preBalanceChangeInDTO.getJoinEnd());
		int sumCount = prePurchaseMoneyChangeMapper.queryPreBalanceChangeCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return preBalanceChangeListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PreBalanceChangeOutDTO> prePurActivityOutDTOs = prePurchaseMoneyChangeMapper.queryBalanceChangeList(param);
		preBalanceChangeListOutDTO.setPreBalanceChanges(prePurActivityOutDTOs);
		return preBalanceChangeListOutDTO;
	}

	@Override
	public PrePurActivityStaticListOutDTO listPrePurActivityStatic(PrePurInDTO prePurInDTO,Page page) throws ApplicationException {
		PrePurActivityStaticListOutDTO prePurActivityStaticListOutDTO = new PrePurActivityStaticListOutDTO();
		prePurActivityStaticListOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		if(prePurInDTO.getAgentId()!=null){
			//代理商的预采购统计 
			 List<Map<String , Object>>  shopRelates=shopGroupRelationMapper.selectShopList( prePurInDTO.getGroupId(),prePurInDTO.getAgentId());
			 if(shopRelates.size()==0){
				 return prePurActivityStaticListOutDTO; 
			 }
			 StringBuffer buffer=new StringBuffer();
			 for(Map<String , Object> t:shopRelates){
				 if(buffer.length()>0){
					 buffer.append(",");
				 }
				 buffer.append(t.get("shop_id"));
			 }
			 param.put("shopIds",buffer.toString());
		}
		if(prePurInDTO.getShopId()!=null){
			 param.put("shopIds",prePurInDTO.getShopId());
		}
		param.put("groupId",prePurInDTO.getGroupId());
		
		if (StringUtils.isNotEmpty(prePurInDTO.getShopName())) {
			param.put("shopName",prePurInDTO.getShopName());
		}
		
        Map<String,Object> staticInfo = prepurchaseActivityStatisMapper.queryPrepurchStaticListInfo(param);
        int sumCount=SysUtils.Object2int(staticInfo.get("totalCount"));
        if(staticInfo.get("staticDate")!=null){
        	prePurActivityStaticListOutDTO.setStaticDate((Date)staticInfo.get("staticDate"));
        }else{
        	prePurActivityStaticListOutDTO.setStaticDate(new Date());
        }
       
        if(staticInfo.get("prePurchaseAmount")!=null){
        	prePurActivityStaticListOutDTO.setPrePurchaseAmount(SysUtils.Object2Long(staticInfo.get("prePurchaseAmount")));
        }else{
        	prePurActivityStaticListOutDTO.setPrePurchaseAmount(0L);
        }
        
        if(staticInfo.get("prePurchaseSettedAmount")!=null){
        	prePurActivityStaticListOutDTO.setPrePurchaseSettedAmount(SysUtils.Object2Long(staticInfo.get("prePurchaseSettedAmount")));
        }else{
        	prePurActivityStaticListOutDTO.setPrePurchaseSettedAmount(0L);
        }
        
        if(staticInfo.get("customerTradeAmount")!=null){
        	prePurActivityStaticListOutDTO.setCustomerTradeAmount(SysUtils.Object2Long(staticInfo.get("customerTradeAmount")));
        }else{
        	prePurActivityStaticListOutDTO.setCustomerTradeAmount(0L);
        }
        
        if(staticInfo.get("customer_pay_amount_total")!=null){
        	prePurActivityStaticListOutDTO.setCustomerPayAmountTotal(SysUtils.Object2Long(staticInfo.get("customer_pay_amount_total")));
        }else{
        	prePurActivityStaticListOutDTO.setCustomerPayAmountTotal(0L);
        }           
        
        
        if(staticInfo.get("staticProfitAmount")!=null){
        	prePurActivityStaticListOutDTO.setStaticProfitAmount(SysUtils.Object2Long(staticInfo.get("staticProfitAmount")));
        }else{
        	prePurActivityStaticListOutDTO.setStaticProfitAmount(0L);
        }
        

        if(staticInfo.get("inPurchaseActivityCount")!=null){
        	prePurActivityStaticListOutDTO.setInPurchaseActivityCount(SysUtils.Object2int(staticInfo.get("inPurchaseActivityCount")));
        }else{
        	prePurActivityStaticListOutDTO.setInPurchaseActivityCount(0);
        }
        
        if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Agents.getType())){
			if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(staticInfo.get("first_agent_id")))){
				prePurActivityStaticListOutDTO.setStaticProfitAmount2(SysUtils.Object2Long(staticInfo.get("first_agent_profit")));
			}else if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(staticInfo.get("second_agent_id")))){
				prePurActivityStaticListOutDTO.setStaticProfitAmount2(SysUtils.Object2Long(staticInfo.get("second_agent_profit")));
			} else if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(staticInfo.get("third_agent_id")))){
				prePurActivityStaticListOutDTO.setStaticProfitAmount2(SysUtils.Object2Long(staticInfo.get("third_agent_profit")));
			}
		}else if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Store.getType())){
			if(ysShopCarMapper.selectShopProfitInfoById(prePurInDTO.getShopId())!=null){
				if(prePurInDTO.getShopId().equals(SysUtils.Object2Long(staticInfo.get("third_agent_id")))){
					prePurActivityStaticListOutDTO.setStaticProfitAmount2(SysUtils.Object2Long(staticInfo.get("third_agent_profit")));
				}
			}
		}
        

        if(staticInfo.get("purchaseActivityCount")!=null){
        	prePurActivityStaticListOutDTO.setPurchaseActivityCount(SysUtils.Object2int(staticInfo.get("purchaseActivityCount")));
        }else{
        	prePurActivityStaticListOutDTO.setPurchaseActivityCount(0);
        }
        
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return prePurActivityStaticListOutDTO;
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PrePurActivityStaticOutDTO> prePurActivityStatics=new ArrayList<PrePurActivityStaticOutDTO>();
		List<Map<String,Object>>result = prepurchaseActivityStatisMapper.queryPrepurchStaticList(param);
		for(Map<String,Object> map:result){
			PrePurActivityStaticOutDTO prePurActivityStaticOutDTO=new PrePurActivityStaticOutDTO();
			prePurActivityStaticOutDTO.setActivityCount(SysUtils.Object2Integer(map.get("activity_count")));
			prePurActivityStaticOutDTO.setAgentName(map.get("agentName")+"");
			prePurActivityStaticOutDTO.setCurrentActivityId(SysUtils.Object2Long(map.get("current_activity_id")));
			prePurActivityStaticOutDTO.setCustomerAmountTotal(SysUtils.Object2Long(map.get("customer_amount_total")));
			prePurActivityStaticOutDTO.setCustomerCountTotal(SysUtils.Object2int(map.get("customer_count_total")));
			//
			prePurActivityStaticOutDTO.setCustomerPayAmountTotal(SysUtils.Object2Long(map.get("customer_pay_amount_total")));
			prePurActivityStaticOutDTO.setEndActivityCount(SysUtils.Object2int(map.get("end_activity_count")));
			prePurActivityStaticOutDTO.setGroupId(SysUtils.Object2Long(map.get("group_id")));
			prePurActivityStaticOutDTO.setId(SysUtils.Object2Long(map.get("id")));
			prePurActivityStaticOutDTO.setInActivityCount(SysUtils.Object2int(map.get("in_activity_count")));
			prePurActivityStaticOutDTO.setPrepurchaseAmountTotal(SysUtils.Object2Long(map.get("prepurchase_amount_total")));
			
			prePurActivityStaticOutDTO.setProfitAmount(SysUtils.Object2Long(map.get("profit_amount")));
			prePurActivityStaticOutDTO.setShopId(SysUtils.Object2Long(map.get("shop_id")));
			prePurActivityStaticOutDTO.setShopName(map.get("shopName")+"");
			prePurActivityStaticOutDTO.setShopSettedAmountTotal(SysUtils.Object2Long(map.get("shop_setted_amount_total")));
			prePurActivityStaticOutDTO.setStaticDate((Date)map.get("static_date"));
			prePurActivityStaticOutDTO.setShopSettingAmountTotal(SysUtils.Object2Long(map.get("shop_setting_amount_total")));
			prePurActivityStaticOutDTO.setStatus(SysUtils.Object2int(map.get("status")));
			prePurActivityStaticOutDTO.setSumCount(sumCount);
			
			if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Agents.getType())){
				if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(map.get("first_agent_id")))){
					prePurActivityStaticOutDTO.setProfitAmount2(SysUtils.Object2Long(map.get("first_agent_profit")));
				}else 
				if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(map.get("second_agent_id")))){
					prePurActivityStaticOutDTO.setProfitAmount2(SysUtils.Object2Long(map.get("second_agent_profit")));
				} else if(prePurInDTO.getAgentId().equals(SysUtils.Object2Long(map.get("third_agent_id")))){
					prePurActivityStaticOutDTO.setProfitAmount2(SysUtils.Object2Long(map.get("third_agent_profit")));
				}
			}else if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Store.getType())){
				if(ysShopCarMapper.selectByPrimaryKey(prePurInDTO.getShopId())!=null){
					if(prePurInDTO.getShopId().equals(SysUtils.Object2Integer(map.get("third_agent_id")))){
						prePurActivityStaticOutDTO.setProfitAmount2(SysUtils.Object2Long(map.get("third_agent_profit")));
					}
				}
			}
			
			prePurActivityStatics.add(prePurActivityStaticOutDTO);
		}
		prePurActivityStaticListOutDTO.setPrePurActivityStatics(prePurActivityStatics);
		return prePurActivityStaticListOutDTO;
	}

	@Override
	public ShopPrePurListOutDTO shopPrePurchaseActivity(PrePurInDTO prePurInDTO,Page page){
		
		ShopPrePurListOutDTO shopPrePurListOutDTO = new ShopPrePurListOutDTO();
		shopPrePurListOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("groupId",prePurInDTO.getGroupId());
		if(prePurInDTO.getStatus()==null){
			param.put("status","-1");
		}else{
			param.put("status",prePurInDTO.getStatus());
		}
     int sumCount = prePurchaseActivityMapper.queryPrePurActivityCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return shopPrePurListOutDTO;
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PrePurActivityOutDTO> prePurActivityStatics = prePurchaseActivityMapper.queryPrePurActivityList(param);
		shopPrePurListOutDTO.setPrePurActivitys(prePurActivityStatics);
		return shopPrePurListOutDTO;
	}
	
	
	
	@Override
	public BaseOutDTO prePurActivityInfo(PrepurchaseInfoInDTO prepurchaseInfoInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		PrePurActivityInfoOutDTO prePurActivityInfoOutDTO=prePurchaseActivityMapper.selectPrePurActivityInfo(prepurchaseInfoInDTO.getId());
		if(prePurActivityInfoOutDTO!=null){
			prePurActivityInfoOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
			return prePurActivityInfoOutDTO;
		}else{
			baseOutDTO.setErrorCode("00X0", "订单不存在");
		}
		return baseOutDTO;
	}

	@Override
	public Boolean updatePrePurUserDiscount(UpdateInPrepurInDTO updateInPrepurInDTO) throws ApplicationException {
		
		Agent agent=agentMapper.selectByPrimaryKey(updateInPrepurInDTO.getAgentId());	
		PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.selectByPrimaryKey(updateInPrepurInDTO.getId());
		if(prePurchaseActivity==null||!prePurchaseActivity.getGroupId().equals(updateInPrepurInDTO.getGroupId())){
			 throw new ApplicationException("参数信息错误");	
		}
		if(!prePurchaseActivity.getStatus().equals(BizEnum.PrePurchaseActivityStatus.in.getType())){
			prePurchaseActivity.setCustomerBenefitAmount(updateInPrepurInDTO.getCustomerBenefitAmount());
		}
		if(StringUtils.isNotBlank(updateInPrepurInDTO.getEndDate())){
			prePurchaseActivity.setEndDate(SysUtils.parseDate(updateInPrepurInDTO.getEndDate(),"yyyy-MM-dd"));
		}
		prePurchaseActivity.setCustomerBenefitAmountNew(updateInPrepurInDTO.getCustomerBenefitAmount());
		prePurchaseActivity.setGmtModified(new Date());
		Long addAmount=updateInPrepurInDTO.getAddPrePurchAmount();
		
		if(addAmount!=null){
			if(agent.getPrePurchaseBalance()<addAmount){
				 throw new ApplicationException("代理商的预采购额度不够");	
			}
			addAmount=addAmount*100;
			prePurchaseActivity.setPrepurchaseAmount(prePurchaseActivity.getPrepurchaseAmount()+addAmount);
			PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
	        prePurchaseMoneyChange.setAgentId(agent.getId());
	        prePurchaseMoneyChange.setAmount(addAmount);
	        prePurchaseMoneyChange.setChangeType(1);
	        prePurchaseMoneyChange.setGmtCreate(new Date());
	        prePurchaseMoneyChange.setGmtModified(new Date());
	        prePurchaseMoneyChange.setGroupId(updateInPrepurInDTO.getGroupId());
	        String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
	        String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
	        prePurchaseMoneyChange.setInfoDesc("代理商商修改预采购活动，调整可用余额"+";调整前余额为"+balanceStr+",调整前额度为"+moneyStr+",调整金额为" +SysUtils.formatNumber(addAmount/100,2));
	        
	        //
	        
	        prePurchaseMoneyChange.setOperateUser(updateInPrepurInDTO.getUpdateUser());
	        prePurchaseMoneyChange.setOperateUserId(updateInPrepurInDTO.getUpdateUserId());
	        prePurchaseMoneyChange.setType(3);//表示代理商创建活动，余额变更
	        
	        long balance = SysUtils.Object2int(agent.getPrePurchaseBalance())-addAmount;
	      	 agent.setPrePurchaseBalance(Long.valueOf(balance).intValue());  
	      	 String descMoney2=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
	      	 agent.setPrePurchaseBalanceDes(descMoney2);
	         prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
	         
	         agentMapper.updateByPrimaryKey(agent);
		}
		return  prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity)>0;
	}

	@Override
	public BaseOutDTO updateReceiceInfo(ReceiceInfoInDTO receiceInfoInDTO) throws ApplicationException {
		
			BaseOutDTO baseOutDTO=new BaseOutDTO();			
			GroupReceiveInfo temp=groupReceiveInfoMapper.selectReceiceInfo(receiceInfoInDTO.getGroupId(),receiceInfoInDTO.getMerchantCode());
			if(temp!=null && !temp.getId().equals(receiceInfoInDTO.getId())){
				baseOutDTO.setErrorCode("0032", "此商户号已经存在");
				return baseOutDTO;
			}
			GroupReceiveInfo groupReiveInfo=groupReceiveInfoMapper.selectByPrimaryKey(receiceInfoInDTO.getId());			
			groupReiveInfo.setGmtModified(new Date());
			groupReiveInfo.setMemo(receiceInfoInDTO.getMemo());
			groupReiveInfo.setMerchantCode(receiceInfoInDTO.getMerchantCode());
			groupReiveInfo.setMerchantName(receiceInfoInDTO.getMerchantName());
			groupReiveInfo.setStatus(receiceInfoInDTO.getStatus());
			groupReiveInfo.setTerminalCode(receiceInfoInDTO.getTerminalCode());
			if(!receiceInfoInDTO.getMerchantCode().equals(groupReiveInfo.getMerchantCode())){
				groupReiveInfo.setTradeAmountPerMonth(0L);
			}
			
			if(receiceInfoInDTO.getChannelFlag()!=null){
				groupReiveInfo.setChannelFlag(receiceInfoInDTO.getChannelFlag());
			}
			
			groupReiveInfo.setUpdateUser(receiceInfoInDTO.getUpdateUser());
			groupReiveInfo.setUpdateUserId(receiceInfoInDTO.getUpdateUserId());
			int result= groupReceiveInfoMapper.updateByPrimaryKey(groupReiveInfo);
			if(result>0){
				baseOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
				return baseOutDTO;
			}else{
				baseOutDTO.setErrorCode("0033", "此数据库操作失败");
				return baseOutDTO;
			}
		}

	@Override
	public boolean finishSycOnStartPrPurs(String dateStr)throws ApplicationException {
		try {
		List<PrePurchaseActivity> onStartPrPurs=prePurchaseActivityMapper.findOnStartPrePurchaseActivity(dateStr,BizEnum.PrePurchaseActivityStatus.approveSuccess.getType());
		
		for(PrePurchaseActivity prePurchaseActivity:onStartPrPurs){
			prePurchaseActivity.setStatus(BizEnum.PrePurchaseActivityStatus.in.getType());
			prePurchaseActivity.setMerchantTodayAmount(0);
			prePurchaseActivity.setMerchantLastDayAmount(0);
			prePurchaseActivity.setLastTradeDate(new Date());
			prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
			//将这个门店的 预采购状态 设置处于预采购状态中
			
			ShopGroupRelation shopGroupRelation= shopGroupRelationMapper.selectShopInfo( prePurchaseActivity.getGroupId(),prePurchaseActivity.getShopId() );
			shopGroupRelation.setPrePurchaseStatus(1);//处于预采购模式
			shopGroupRelation.setGmtModified(new Date());
			shopGroupRelationMapper.updateByPrimaryKey(shopGroupRelation);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw new ApplicationException("更新数据错误");
	}
		return true;
	}

	@Override
	public boolean finishSycOnEndPrPurs(String dateStr) throws ApplicationException{
		try {
		List<PrePurchaseActivity> onEndPrPurs=prePurchaseActivityMapper.findOnEndPrePurchaseActivity(dateStr,BizEnum.PrePurchaseActivityStatus.in.getType());
		for(PrePurchaseActivity prePurchaseActivity:onEndPrPurs){
			prePurchaseActivity.setStatus(BizEnum.PrePurchaseActivityStatus.end.getType());
			prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
			ShopGroupRelation shopGroupRelation= shopGroupRelationMapper.selectShopInfo( prePurchaseActivity.getGroupId(),prePurchaseActivity.getShopId() );
			shopGroupRelation.setPrePurchaseStatus(0);//处于预采购模式
			shopGroupRelation.setGmtModified(new Date());
			shopGroupRelationMapper.updateByPrimaryKey(shopGroupRelation);
			//将预采购的剩余的额度加回到代理商
			
			Agent agent = agentMapper.selectByPrimaryKey(prePurchaseActivity.getAgentId());
			
			long amount=(prePurchaseActivity.getPrepurchaseAmount()-prePurchaseActivity.getCustomerSaleAmount()) * prePurchaseActivity.getAgentBenefitAmount()/100 ;
			if (prePurchaseActivity.getRiskAmount() < 0) {
				 amount = amount + prePurchaseActivity.getRiskAmount();//风险值 是负值
			}		
			int result=0;
			if(amount>0){
				PrePurchaseMoneyChange prePurchaseMoneyChange = new PrePurchaseMoneyChange();
				prePurchaseMoneyChange.setAgentId(agent.getId());
				prePurchaseMoneyChange.setAmount(amount);
				prePurchaseMoneyChange.setChangeType(1);
				prePurchaseMoneyChange.setGmtCreate(new Date());
				prePurchaseMoneyChange.setGmtModified(new Date());
				prePurchaseMoneyChange.setGroupId(prePurchaseActivity.getGroupId());
				String balanceStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance()) / 100, 2);
				String moneyStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney()) / 100, 2);
				prePurchaseMoneyChange
						.setInfoDesc("提前结束已经审核成功的活动，还原创建时减入金额到可用余额" + ";调整前余额为" + balanceStr + ",额度为" + moneyStr + ",调整金额为" + SysUtils.formatNumber(amount / 100, 2));

				prePurchaseMoneyChange.setOperateUser("系统任务执行");
				prePurchaseMoneyChange.setOperateUserId(0L);
				prePurchaseMoneyChange.setType(4);// 代理商删除活动

				int balance = SysUtils.Object2int(agent.getPrePurchaseBalance()) + Long.valueOf(amount).intValue();
				agent.setPrePurchaseBalance(balance);
				String descMoney2 = SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
				agent.setPrePurchaseBalanceDes(descMoney2);

				result =prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
				if(result<=0){
					throw new ApplicationException("更新数据错误");
				}
				result =agentMapper.updateByPrimaryKey(agent);
				if(result<=0){
					throw new ApplicationException("更新数据错误");
				}		
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw new ApplicationException("更新数据错误");
	}
		return true;
	}

	@Override
	public boolean finishSycUserSaleAmount() throws ApplicationException{
		try {
			List<PrePurchaseActivity> onEndPrPurs=prePurchaseActivityMapper.findCustomerBenefitAmountUpdateActivity(BizEnum.PrePurchaseActivityStatus.in.getType());
			for(PrePurchaseActivity prePurchaseActivity:onEndPrPurs){
				prePurchaseActivity.setCustomerBenefitAmount(prePurchaseActivity.getCustomerBenefitAmountNew());
				prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException("更新数据错误");
		}
		return true;
	}

	@Override
	public boolean finishPrePursMerchantSetted(Date date) throws ApplicationException{
		try {
			List<PrePurchaseActivity>  prePurchaseActivities=new ArrayList<PrePurchaseActivity>();
			/**
			 * 查询交易时间是昨天 ，今日交易金额 不为0 的记录
			 */
			String	dateStr = DateUtil.fomatDate(date, DateUtil.sdfDay);
			List<PrePurchaseActivity> prePurchaseActivities2=prePurchaseActivityMapper.findTodaySettedPurch(dateStr);
			
			if(prePurchaseActivities2!=null&&prePurchaseActivities2.size()>0){
				prePurchaseActivities.addAll(prePurchaseActivities2);
			}
			/**
			 * 查询交易时间是今天，昨日交易金额 不为0 的记录
			 */
			String DateStr2= DateUtil.fomatDate(DateUtil.getAfterDay(date,-1),DateUtil.sdfDay);
			List<PrePurchaseActivity> prePurchaseActivities3=prePurchaseActivityMapper.findYestodaySettedPurch(DateStr2);
			
			if(prePurchaseActivities3!=null&&prePurchaseActivities3.size()>0){
				prePurchaseActivities.addAll(prePurchaseActivities3);
			}
		
		for(PrePurchaseActivity prePurchaseActivity:prePurchaseActivities){
			//支付平台请求对象创建
			int tradeAmount= prePurchaseActivity.getMerchantTodayAmount();
			String orderNum= UtilFun.createOrderNum();
			ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(prePurchaseActivity.getGroupId(),prePurchaseActivity.getShopId());
		    Group  group=groupMapper.selectByPrimaryKey(prePurchaseActivity.getGroupId());
			PayBalanceChange   payBalanceChange = PayBalanceChange.initialize(group.getPayGroupCode(),shopGroupRelation.getPayMerchantCode(),tradeAmount+"" ,
                    "1",orderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");

			 PayResult payResult = IPayAPI.consumptionBalanceChangeMerchant(payBalanceChange);
             if(!payResult.getRespCode().equals("0000")) {
            	 throw new ApplicationException("审核失败，商户余额变更错误");
             }else{
            	 //交易记录创建
            	 TradeOffline  tradeOffline = new TradeOffline();
                 tradeOffline.setGmtCreate(new Date());
                 tradeOffline.setGroupId(prePurchaseActivity.getGroupId());
                 tradeOffline.setOrderId(orderNum);
                 tradeOffline.setReceiverId(prePurchaseActivity.getShopId()+"");
                 Shop shop=shopMapper.selectByPrimaryKey(prePurchaseActivity.getShopId());
                 tradeOffline.setReceiverName(shop.getMerchantName());
                 tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
                 tradeOffline.setTransactionType((byte) BizEnum.TransactionType.AddBalanceMerchant.getType());
                 tradeOffline.setOrderAmount(tradeAmount);
                 tradeOffline.setRealAmount(tradeAmount);
                 tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
                 tradeOffline.setIsWallet(true);
                 tradeOffline.setGmtCreate(new Date());
                 tradeOffline.setDiscountAmount(0);
                 tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                 tradeOffline.setTransOrderNo(payResult.getOrderId());
                 tradeOffline.setPayOrderid(payBalanceChange.getOrgOrderNum());
                 tradeOffline.setMemo("商户处于预采购模式，每天用户消费金额 ，结算算商户的钱包");
                 tradeOfflineMapper.insertSelective(tradeOffline);
                 String lastTradeDate=SysUtils.formatDate(prePurchaseActivity.getLastTradeDate(),"yyyy-MM-dd");
                 if(lastTradeDate.equals(SysUtils.formatDate(date,"yyyy-MM-dd"))){
                	 prePurchaseActivity.setMerchantLastDayAmount(0);
                 }else{
                	 prePurchaseActivity.setMerchantTodayAmount(0);
                 }
                 prePurchaseActivity.setMerchantSettedAmount(prePurchaseActivity.getMerchantSettedAmount()+tradeAmount);
                 prePurchaseActivity.setLastTradeDate(new Date());
                
             }
			prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw new ApplicationException("更新数据错误");
	}
		return true;
	}

	@Override
	public BaseOutDTO finishEndPrePurActivity(PrePurInDTO prePurInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO = new BaseOutDTO();

		PrePurchaseActivity prePurchaseActivity = prePurchaseActivityMapper.selectByPrimaryKey(prePurInDTO.getId());
		if (prePurchaseActivity.getStatus().equals(BizEnum.PrePurchaseActivityStatus.approveSuccess.getType())
				||prePurchaseActivity.getStatus().equals(BizEnum.PrePurchaseActivityStatus.in.getType())) {
		 //	只有 在成功 或者待开始的时候 金额结束
		}else{
			baseOutDTO.setErrorCode("0032", "当前预采购活动不能进行次操作");
			return baseOutDTO;
		}
		Agent agent = agentMapper.selectByPrimaryKey(prePurInDTO.getAgentId());
		ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(prePurInDTO.getGroupId(), prePurchaseActivity.getShopId());
		if (agent == null || shopGroupRelation == null || !agent.getGroupId().equals(prePurInDTO.getGroupId())) {
			baseOutDTO.setErrorCode("0032", "参数信息错误");
			return baseOutDTO;
		}
		if (!prePurchaseActivity.getAgentId().equals(prePurInDTO.getAgentId())) {
			baseOutDTO.setErrorCode("0032", "您无权结束此活动");
			return baseOutDTO;
		}
		// 将代理商的额度 ---
		String descBalance = SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
		if (!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())) {
			throw new ApplicationException("代理商的余额信息不正常，请联系客服");
		}

		String descMoney = SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
		if (!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())) {
			throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
		}
		
		long amount=(prePurchaseActivity.getPrepurchaseAmount()-prePurchaseActivity.getCustomerSaleAmount()) * prePurchaseActivity.getAgentBenefitAmount()/100 ;
		if (prePurchaseActivity.getRiskAmount() < 0) {
			 amount = amount + prePurchaseActivity.getRiskAmount();//风险值 是负值
		}		
		int result=0;
		if(amount>0){
			PrePurchaseMoneyChange prePurchaseMoneyChange = new PrePurchaseMoneyChange();
			prePurchaseMoneyChange.setAgentId(agent.getId());
			prePurchaseMoneyChange.setAmount(amount);
			prePurchaseMoneyChange.setChangeType(1);
			prePurchaseMoneyChange.setGmtCreate(new Date());
			prePurchaseMoneyChange.setGmtModified(new Date());
			prePurchaseMoneyChange.setGroupId(prePurchaseActivity.getGroupId());
			String balanceStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance()) / 100, 2);
			String moneyStr = SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney()) / 100, 2);
			prePurchaseMoneyChange
					.setInfoDesc("提前结束已经审核成功的活动，还原创建时减入金额到可用余额" + ";调整前余额为" + balanceStr + ",额度为" + moneyStr + ",调整金额为" + SysUtils.formatNumber(amount / 100, 2));

			prePurchaseMoneyChange.setOperateUser(prePurInDTO.getUpdateUser());
		    prePurchaseMoneyChange.setOperateUserId(prePurInDTO.getUpdateUserId());
		      
			prePurchaseMoneyChange.setType(4);// 代理商删除活动

			int balance = SysUtils.Object2int(agent.getPrePurchaseBalance()) + Long.valueOf(amount).intValue();
			agent.setPrePurchaseBalance(balance);
			String descMoney2 = SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
			agent.setPrePurchaseBalanceDes(descMoney2);

			result =prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
			if(result<=0){
				baseOutDTO.setErrorCode("0033", "此数据库操作失败");
				return baseOutDTO;
			}
			result =agentMapper.updateByPrimaryKey(agent);
			if(result<=0){
				baseOutDTO.setErrorCode("0033", "此数据库操作失败");
				return baseOutDTO;
			}		
		}
		
		
		prePurchaseActivity.setStatus(BizEnum.PrePurchaseActivityStatus.end.getType());
		prePurchaseActivity.setGmtModified(new Date());
		result =prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
		if(result<=0){
			baseOutDTO.setErrorCode("0033", "此数据库操作失败");
			return baseOutDTO;
		}
		shopGroupRelation.setPrePurchaseStatus(0);//处于预采购模式
		shopGroupRelation.setGmtModified(new Date());
		shopGroupRelationMapper.updateByPrimaryKey(shopGroupRelation);
		baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
		return baseOutDTO;
		
	}

	/**
	 * 预采购活动统计
	 */
	@Override
	public void finishPrePursStaticByShop() {
		
		List<Map<String,Object>> staticPreStatics=prePurchaseActivityMapper.selectGroupByShopAndGroup();
		for(Map<String ,Object> temp:staticPreStatics){
			Long groupId=SysUtils.Object2Long(temp.get("groupId")+"");
			Long shopId=SysUtils.Object2Long(temp.get("shopId")+"");
			PrepurchaseActivityStatis prepurchaseActivityStatis=prepurchaseActivityStatisMapper.selectByShopAndGroup(groupId,shopId);
			if(prepurchaseActivityStatis==null){
				prepurchaseActivityStatis=	new PrepurchaseActivityStatis();
				prepurchaseActivityStatis.setGroupId(groupId);
				prepurchaseActivityStatis.setShopId(shopId);
			}
			Integer activityCount=SysUtils.Object2int(temp.get("activityCount")+"");
			prepurchaseActivityStatis.setActivityCount(activityCount);
			Long currentActivityId=SysUtils.Object2Long(temp.get("currentActivityId")+"");
			prepurchaseActivityStatis.setCurrentActivityId(currentActivityId);
			Long customerAmountTotal=SysUtils.Object2Long(temp.get("customerAmountTotal")+"");
			prepurchaseActivityStatis.setCustomerAmountTotal(customerAmountTotal);
			Long customerPayAmount=SysUtils.Object2Long(temp.get("customerPayAmount")+"");
			prepurchaseActivityStatis.setCustomerPayAmountTotal(customerPayAmount);
			Long shopSettingAmountTotal=SysUtils.Object2Long(temp.get("shopSettingAmountTotal")+"");
			prepurchaseActivityStatis.setShopSettingAmountTotal(shopSettingAmountTotal);
			//
			Long merchantSettedAmount=SysUtils.Object2Long(temp.get("merchantSettedAmount")+"");
			prepurchaseActivityStatis.setShopSettedAmountTotal(merchantSettedAmount);
            prepurchaseActivityStatis.setCustomerCountTotal(SysUtils.Object2int(temp.get("customerCountTotal")+""));
			
			Long prepurchaseAmountTotal=SysUtils.Object2Long(temp.get("prepurchaseAmountTotal")+"");
			
			prepurchaseActivityStatis.setPrepurchaseAmountTotal(prepurchaseAmountTotal);
			Map<String ,Object>param=new HashMap<String,Object>();
			param.put("shopId", shopId);
			param.put("groupId", groupId);
			param.put("status", BizEnum.PrePurchaseActivityStatus.end.getType());
			int result=prePurchaseActivityMapper.queryPrePurActivityCount(param);
			prepurchaseActivityStatis.setEndActivityCount(result);
			Map<String ,Object>param2=new HashMap<String,Object>();
			param2.put("shopId", shopId);
			param2.put("groupId", groupId);
			param2.put("status", BizEnum.PrePurchaseActivityStatus.in.getType());
			int result2=prePurchaseActivityMapper.queryPrePurActivityCount(param2);
			prepurchaseActivityStatis.setInActivityCount(result2);
			
//			Long profitAmount=SysUtils.Object2Long(temp.get("profitAmount")+"");
			
			//插叙这个门店 大商户 进行中或者结束的预采购活动
			List<PrePurchaseActivity>  prePurchase=prePurchaseActivityMapper.selectInAndEndPrePurchByShopAndGroup(groupId,shopId);		
			long profitAmount=0l;
			Long firstAgentId=0L;
			int firstAgentProfit=0;		
			Long secondAgentId=0L;		
			int secondAgentProfit=0;			
			Long thirdAgentId=0L;
			int thirdAgentProfit=0;
			
			
			//每个门店和代理不可改变
			for(PrePurchaseActivity prePurchaseActivity:prePurchase){
				Map<String,Object> profitStatic=profitMapper.findProfitStaticByPrePurch(prePurchaseActivity.getId());
				profitAmount=profitAmount+SysUtils.Object2int(profitStatic.get("profit"));
				Long tempAgent=SysUtils.Object2Long(profitStatic.get("firstAgentId"));
				if(tempAgent!=null&&tempAgent>0){
					firstAgentId=tempAgent;
				}
				
				firstAgentProfit=firstAgentProfit+SysUtils.Object2int(profitStatic.get("firstAgentProfit"));
				tempAgent=SysUtils.Object2Long(profitStatic.get("secondAgentId"));
				if(tempAgent!=null&&tempAgent>0){
					secondAgentId=tempAgent;
				}
				secondAgentProfit=secondAgentProfit+SysUtils.Object2int(profitStatic.get("secondAgentProfit"));				
				tempAgent=SysUtils.Object2Long(profitStatic.get("thirdAgentId"));
				if(tempAgent!=null&&tempAgent>0){
					thirdAgentId=tempAgent;
				}
				thirdAgentProfit=thirdAgentProfit+SysUtils.Object2int(profitStatic.get("thirdAgentProfit"));
			  }
			
			prepurchaseActivityStatis.setProfitAmount(profitAmount);
//			Long profitAmount2=SysUtils.Object2Long(temp.get("profitAmount2")+"");
			prepurchaseActivityStatis.setFirstAgentId(firstAgentId);
			prepurchaseActivityStatis.setFirstAgentProfit(firstAgentProfit);
			
			prepurchaseActivityStatis.setSecondAgentId(secondAgentId);
			prepurchaseActivityStatis.setSecondAgentProfit(secondAgentProfit);
			
			prepurchaseActivityStatis.setThirdAgentId(thirdAgentId);
			prepurchaseActivityStatis.setThirdAgentProfit(thirdAgentProfit);
			
			
			prepurchaseActivityStatis.setStaticDate(new Date());
			if(prepurchaseActivityStatis.getId()!=null&&prepurchaseActivityStatis.getId()>0){
				prepurchaseActivityStatisMapper.updateByPrimaryKey(prepurchaseActivityStatis);
			}else{
				prepurchaseActivityStatisMapper.insert(prepurchaseActivityStatis);
			}
			
			
		}
		
	}

	@Override
	public ShopPrePurListOutDTO findShopPrePurActivityStaic(PrePurInDTO prePurInDTO, Page page) throws ApplicationException {
		ShopPrePurListOutDTO shopPrePurListOutDTO=new ShopPrePurListOutDTO();
        Map<String,Object> param=new HashMap<String,Object>();
		param.put("shopId",prePurInDTO.getShopId());
		param.put("groupId",prePurInDTO.getGroupId());
		param.put("status",prePurInDTO.getStatus());
		param.put("joinStart",prePurInDTO.getJoinStart());
		param.put("joinEnd",prePurInDTO.getJoinEnd());
		int sumCount = prePurchaseActivityMapper.queryPrePurActivityCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return shopPrePurListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PrePurActivityOutDTO> prePurActivityOutDTOs = prePurchaseActivityMapper.queryPrePurActivityList(param);
		shopPrePurListOutDTO.setPrePurActivitys(prePurActivityOutDTOs);
		
		
		Map<String ,Object>param2=new HashMap<String,Object>();
		param2.put("shopId",prePurInDTO.getShopId());
		param2.put("groupId",prePurInDTO.getGroupId());
		param2.put("status", BizEnum.PrePurchaseActivityStatus.end.getType());
		int endActivityCount=prePurchaseActivityMapper.queryPrePurActivityCount(param2);
		shopPrePurListOutDTO.setEndActivityCount(endActivityCount);
		
		Map<String,Object> staticResult=prePurchaseActivityMapper.selectStaticByShopAndGroup(prePurInDTO.getGroupId(),prePurInDTO.getShopId());
		Integer activityCount=SysUtils.Object2int(staticResult.get("activityCount")+"");
		shopPrePurListOutDTO.setActivityCount(activityCount);
		Long shopSettedAmountTotal=SysUtils.Object2Long(staticResult.get("merchantSettedAmount")+"");
		shopPrePurListOutDTO.setShopSettedAmountTotal(shopSettedAmountTotal);
		
		Long shopSettingAmountTotal=SysUtils.Object2Long(staticResult.get("shopSettingAmountTotal")+"");
		shopPrePurListOutDTO.setShopSettingAmountTotal(shopSettingAmountTotal);
		Long prepurchaseAmountTotal=SysUtils.Object2Long(staticResult.get("prepurchaseAmountTotal")+"");
		
		shopPrePurListOutDTO.setPrepurchaseAmountTotal(prepurchaseAmountTotal);
		
		/**
		 * 只统计 预采购进行中 和已经完成的
		 */
		Long shopPreSettedAmountTotal=prePurchaseActivityMapper.selectStaticPreSettedByShopAndGroup(prePurInDTO.getGroupId(),prePurInDTO.getShopId());
		
		shopPrePurListOutDTO.setShopPreSettedAmountTotal(shopPreSettedAmountTotal);
		
        Long customerAmountTotal=SysUtils.Object2Long(staticResult.get("customerAmountTotal")+"");
		
		shopPrePurListOutDTO.setCustomerAmountTotal(customerAmountTotal);
		
		 Long customerPayAmount=SysUtils.Object2Long(staticResult.get("customerPayAmount")+"");
			
			shopPrePurListOutDTO.setCustomerPayAmount(customerPayAmount);
		
		PrepurchaseActivityStatis prepurchaseActivityStatis=prepurchaseActivityStatisMapper.selectByShopAndGroup(prePurInDTO.getGroupId(),prePurInDTO.getShopId());
		
		PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.selectByPrimaryKey(prepurchaseActivityStatis.getCurrentActivityId());
		shopPrePurListOutDTO.setStatus(prePurchaseActivity.getStatus());
		shopPrePurListOutDTO.setAgentName(staticResult.get("agentName")+"");
		
		List<PrePurchaseActivity>  prePurchase=prePurchaseActivityMapper.selectInAndEndPrePurchByShopAndGroup(prePurInDTO.getGroupId(),prePurInDTO.getShopId());		
		Long profitAmount=0l;
		Long firstAgentId=null;
		Long firstAgentProfit=0L;		
		Long secondAgentId=null;		
		Long secondAgentProfit=0L;			
		Long thirdAgentId=null;
		Long thirdAgentProfit=0L;
		
		//每个门店和代理不可改变
		for(PrePurchaseActivity prePurchaseActivity2:prePurchase){
			Map<String,Object> profitStatic=profitMapper.findProfitStaticByPrePurch(prePurchaseActivity2.getId());
			profitAmount=profitAmount+SysUtils.Object2int(profitStatic.get("profit"));
			Long temp=SysUtils.Object2Long(profitStatic.get("firstAgentId"));
			if(temp!=null&&temp>0){
				firstAgentId=temp;
			}		
			firstAgentProfit=firstAgentProfit+SysUtils.Object2int(profitStatic.get("firstAgentProfit"));
			temp=SysUtils.Object2Long(profitStatic.get("secondAgentId"));
			if(temp!=null&&temp>0){
				secondAgentId=temp;
			}
			temp=SysUtils.Object2Long(profitStatic.get("thirdAgentId"));
			secondAgentProfit=secondAgentProfit+SysUtils.Object2int(profitStatic.get("secondAgentProfit"));				
			if(temp!=null&&temp>0){
				thirdAgentId=temp;
			}
			thirdAgentProfit=thirdAgentProfit+SysUtils.Object2int(profitStatic.get("thirdAgentProfit"));
		  }		
		
		shopPrePurListOutDTO.setProfitAmount(profitAmount);
		shopPrePurListOutDTO.setFirstAgentId(firstAgentId);
		shopPrePurListOutDTO.setFirstAgentProfit(firstAgentProfit);	
		shopPrePurListOutDTO.setSecondAgentId(secondAgentId);
		shopPrePurListOutDTO.setSecondAgentProfit(secondAgentProfit);			
		shopPrePurListOutDTO.setThirdAgentId(thirdAgentId);
		shopPrePurListOutDTO.setThirdAgentProfit(thirdAgentProfit);	
		
		if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Agents.getType())){
			if(prePurInDTO.getAgentId().equals(firstAgentId)){
				shopPrePurListOutDTO.setProfitAmount(firstAgentProfit);
			}else if(prePurInDTO.getAgentId().equals(secondAgentId)){
				shopPrePurListOutDTO.setProfitAmount(secondAgentProfit);
			} else if(prePurInDTO.getAgentId().equals(thirdAgentId)){
				shopPrePurListOutDTO.setProfitAmount(thirdAgentProfit);
			}
		}else if(prePurInDTO.getLoginUserType().equals(CommonEnum.UserType.Store.getType())){
			if(ysShopCarMapper.selectByPrimaryKey(prePurInDTO.getShopId())!=null){
				if(prePurInDTO.getShopId().equals(thirdAgentId)){
					shopPrePurListOutDTO.setProfitAmount(thirdAgentProfit);
				}
			}
		}
		
		shopPrePurListOutDTO.setShopName(staticResult.get("shopName")+"");
		return shopPrePurListOutDTO;
	}
	
	

	@Override
	public PrePurActivityMoreInfoOutDTO prePurActivityMoreInfo(PrepurchaseInfoInDTO prepurchaseInfoInDTO, Page page) throws ApplicationException {
		PrePurActivityMoreInfoOutDTO prePurActivityMoreInfoOutDTO=new PrePurActivityMoreInfoOutDTO();
		PrePurActivityInfoOutDTO prePurActivityInfoOutDTO=prePurchaseActivityMapper.selectPrePurActivityInfo(prepurchaseInfoInDTO.getId());
		if(prePurActivityInfoOutDTO==null){
			prePurActivityMoreInfoOutDTO.setErrorCode("00X0", "订单不存在");
			return prePurActivityMoreInfoOutDTO;
		}
	
		prePurActivityMoreInfoOutDTO.setAgentBenefitAmount(prePurActivityInfoOutDTO.getAgentBenefitAmount());
		prePurActivityMoreInfoOutDTO.setAgentId(prePurActivityInfoOutDTO.getAgentId());
		prePurActivityMoreInfoOutDTO.setAgentName(prePurActivityInfoOutDTO.getAgentName());
		prePurActivityMoreInfoOutDTO.setApproveInfo(prePurActivityInfoOutDTO.getApproveInfo());
		prePurActivityMoreInfoOutDTO.setApproveUserId(prePurActivityInfoOutDTO.getApproveUserId());
		prePurActivityMoreInfoOutDTO.setApproveUserId(prePurActivityInfoOutDTO.getApproveUserId());
		prePurActivityMoreInfoOutDTO.setCreateUserId(prePurActivityInfoOutDTO.getCreateUserId());
		prePurActivityMoreInfoOutDTO.setCustomerBenefitAmount(prePurActivityInfoOutDTO.getCustomerBenefitAmount());
		prePurActivityMoreInfoOutDTO.setCustomerBenefitAmountNew(prePurActivityInfoOutDTO.getCustomerBenefitAmountNew());
		prePurActivityMoreInfoOutDTO.setCustomerSaleAmount(prePurActivityInfoOutDTO.getCustomerSaleAmount());
		prePurActivityMoreInfoOutDTO.setCustomerSaleCount(prePurActivityInfoOutDTO.getCustomerSaleCount());
		prePurActivityMoreInfoOutDTO.setEndDate(prePurActivityInfoOutDTO.getEndDate());
		prePurActivityMoreInfoOutDTO.setGmtCreate(prePurActivityInfoOutDTO.getGmtCreate());
		prePurActivityMoreInfoOutDTO.setGmtModified(prePurActivityInfoOutDTO.getGmtModified());
		prePurActivityMoreInfoOutDTO.setGroupId(prePurActivityInfoOutDTO.getGroupId());
		prePurActivityMoreInfoOutDTO.setId(prePurActivityInfoOutDTO.getId());
		prePurActivityMoreInfoOutDTO.setLastTradeDate(prePurActivityInfoOutDTO.getLastTradeDate());
	
		prePurActivityMoreInfoOutDTO.setMerchantLastDayAmount(prePurActivityInfoOutDTO.getMerchantLastDayAmount());
		prePurActivityMoreInfoOutDTO.setMerchantPresetAmount(prePurActivityInfoOutDTO.getMerchantPresetAmount());
		prePurActivityMoreInfoOutDTO.setMerchantTodayAmount(prePurActivityInfoOutDTO.getMerchantTodayAmount());
		prePurActivityMoreInfoOutDTO.setPrepurchaseAmount(prePurActivityInfoOutDTO.getPrepurchaseAmount());
		prePurActivityMoreInfoOutDTO.setPrepurchaseType(prePurActivityInfoOutDTO.getPrepurchaseType());
		prePurActivityMoreInfoOutDTO.setRiskAmount(prePurActivityInfoOutDTO.getRiskAmount());
		prePurActivityMoreInfoOutDTO.setShopId(prePurActivityInfoOutDTO.getShopId());
		prePurActivityMoreInfoOutDTO.setShopName(prePurActivityInfoOutDTO.getShopName());
		prePurActivityMoreInfoOutDTO.setStartDate(prePurActivityInfoOutDTO.getStartDate());
		prePurActivityMoreInfoOutDTO.setStatus(prePurActivityInfoOutDTO.getStatus());
		
//	   if()
    	prePurActivityMoreInfoOutDTO.setLevelName(prePurActivityInfoOutDTO.getAgentLevel()+"级代理商");
		
	    Map<String,Object> param=new HashMap<String,Object>();
		param.put("prePurActivityId",prepurchaseInfoInDTO.getId());
		param.put("groupId",prepurchaseInfoInDTO.getGroupId());
		param.put("joinEnd",prepurchaseInfoInDTO.getJoinEnd());
		param.put("joinStart",prepurchaseInfoInDTO.getJoinStart());
		param.put("transactionStatus",prepurchaseInfoInDTO.getTransactionStatus());
		param.put("payType",prepurchaseInfoInDTO.getPayType());
		
		
		Map<String,Object> map= tradeOfflineMapper.queryPrepurshTradeStatic(param);
		int sumCount=SysUtils.Object2int(map.get("countNum"));
		page.setTotalResult(sumCount);
		if(sumCount<=0)
		{
			prePurActivityMoreInfoOutDTO.setTotalOrderAmount(0l);
			prePurActivityMoreInfoOutDTO.setTotalPayAmount(0l);
			prePurActivityMoreInfoOutDTO.setTotalPayCount(0);
			return prePurActivityMoreInfoOutDTO;
		}else{
			prePurActivityMoreInfoOutDTO.setTotalOrderAmount(SysUtils.Object2Long(map.get("totalOrderAmount")));
			prePurActivityMoreInfoOutDTO.setTotalPayAmount(SysUtils.Object2Long(map.get("totalPayAmount")));
			prePurActivityMoreInfoOutDTO.setTotalPayCount(sumCount);
		}
	
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		List<TradeOffline> tradeLists = tradeOfflineMapper.queryPrepurshTradeList(param);
		prePurActivityMoreInfoOutDTO.setTradeList(tradeLists);
		
		
		return prePurActivityMoreInfoOutDTO;
	}

	
	@Override
	public PreTradeOutDTO prePurchTrades(PrepurchaseInfoInDTO prepurchaseInfoInDTO) throws ApplicationException {

	    Map<String,Object> param=new HashMap<String,Object>();
		param.put("prePurActivityId",prepurchaseInfoInDTO.getId());
		param.put("groupId",prepurchaseInfoInDTO.getGroupId());
		param.put("joinEnd",prepurchaseInfoInDTO.getJoinEnd());
		param.put("joinStart",prepurchaseInfoInDTO.getJoinStart());
		param.put("transactionStatus",prepurchaseInfoInDTO.getTransactionStatus());
		param.put("payType",prepurchaseInfoInDTO.getPayType());
		
		Map<String,Object> map= tradeOfflineMapper.queryPrepurshTradeStatic(param);
		int sumCount=SysUtils.Object2int(map.get("countNum"));
		PreTradeOutDTO preTradeOutDTO=new PreTradeOutDTO();
		if(sumCount<=0)
		{
			preTradeOutDTO.setTotalOrderAmount(0l);
			preTradeOutDTO.setTotalPayAmount(0l);
			preTradeOutDTO.setTotalPayCount(0);
			return preTradeOutDTO;
		}else{
			preTradeOutDTO.setTotalOrderAmount(SysUtils.Object2Long(map.get("totalOrderAmount")));
			preTradeOutDTO.setTotalPayAmount(SysUtils.Object2Long(map.get("totalPayAmount")));
			preTradeOutDTO.setTotalPayCount(sumCount);
		}
		
		List<TradeOffline> tradeLists = tradeOfflineMapper.queryPrepurshTradeList(param);
		List<PreTradeBean>tradeList=new ArrayList<PreTradeBean>();
		
		for(TradeOffline tradeOffline:tradeLists){
			PreTradeBean preTradeBean=new PreTradeBean();
			preTradeBean.setDiscountAmount(tradeOffline.getDiscountAmount());
			preTradeBean.setDividableAmount(tradeOffline.getDividableAmount());
			preTradeBean.setFee(tradeOffline.getShopFee());
			preTradeBean.setGmtCreate(tradeOffline.getGmtCreate());
			preTradeBean.setId(tradeOffline.getId());
			preTradeBean.setOrderAmount(tradeOffline.getOrderAmount());
			preTradeBean.setPayerName(tradeOffline.getPayerName());
			preTradeBean.setPayType(Integer.valueOf(tradeOffline.getPayType()));
			preTradeBean.setRealAmount(tradeOffline.getRealAmount());
			preTradeBean.setShopName(tradeOffline.getReceiverName());
			preTradeBean.setTransactionStatus(Integer.valueOf(tradeOffline.getTransactionStatus()));
			preTradeBean.setTransactionType(Integer.valueOf(tradeOffline.getTransactionType()));
			preTradeBean.setOrderNo(tradeOffline.getPayOrderid());
			preTradeBean.setTransOrderNo(tradeOffline.getTransOrderNo());
			tradeList.add(preTradeBean);
		}
		
		preTradeOutDTO.setId(prepurchaseInfoInDTO.getId());
		preTradeOutDTO.setTradeList(tradeList);
		return preTradeOutDTO;
	}
	
	
	@Override
	public PreBalanceChangeListOutDTO listPreBalanceUse(PreBalanceChangeInDTO preBalanceChangeInDTO, Page page) throws ApplicationException {
		PreBalanceChangeListOutDTO preBalanceChangeListOutDTO = new PreBalanceChangeListOutDTO();
		preBalanceChangeListOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("agentId",preBalanceChangeInDTO.getAgentId());	
		param.put("groupId",preBalanceChangeInDTO.getGroupId());
		param.put("joinStart",preBalanceChangeInDTO.getJoinStart());
		param.put("joinEnd",preBalanceChangeInDTO.getJoinEnd());
		int sumCount = prePurchaseMoneyChangeMapper.queryPreBalanceUseCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return preBalanceChangeListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<PreBalanceChangeOutDTO> prePurActivityOutDTOs = prePurchaseMoneyChangeMapper.queryPreBalanceUseList(param);
		preBalanceChangeListOutDTO.setPreBalanceChanges(prePurActivityOutDTOs);
		return preBalanceChangeListOutDTO;
	}

	@Override
	public BaseOutDTO finishAddPrePurBalance(DoAddPrePurchBalanceInDTO doAddPrePurchBalanceInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		PrePurchaseActivity prePurchaseActivity=prePurchaseActivityMapper.selectByPrimaryKey(doAddPrePurchBalanceInDTO.getId());
		//操作之前验证数据安全性是否完整
		if(prePurchaseActivity==null){
			baseOutDTO.setErrorCode("00X0", "订单不存在");
			return baseOutDTO;
		}
		Agent agent=agentMapper.selectByPrimaryKey(prePurchaseActivity.getAgentId());
		if(SysUtils.Object2int(agent.getPrePurchaseBalance())!=0){
			
			String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
			if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
				throw new ApplicationException("代理商的余额信息不正常，请联系客服");
			}
		}
		
       if(SysUtils.Object2int(agent.getPrePurchaseMoney())!=0){
    	   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
			if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
				throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
			}
			
		}
       //
       PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
       prePurchaseMoneyChange.setAgentId(agent.getId());
       
       prePurchaseMoneyChange.setAttachFile(doAddPrePurchBalanceInDTO.getFileUrl());
       prePurchaseMoneyChange.setAmount(prePurchaseActivity.getRiskAmount()*-1);
       prePurchaseMoneyChange.setChangeType(1);
       prePurchaseMoneyChange.setGmtCreate(new Date());
       prePurchaseMoneyChange.setGmtModified(new Date());
       prePurchaseMoneyChange.setGroupId(doAddPrePurchBalanceInDTO.getGroupId());
       String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
       String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
       prePurchaseMoneyChange.setInfoDesc(doAddPrePurchBalanceInDTO.getInfoDesc()+";渠道调整前余额为"+balanceStr+",额度为"+moneyStr
    		   +",调整金额为" +SysUtils.formatNumber(prePurchaseMoneyChange.getAmount()/100,2));
       prePurchaseMoneyChange.setOperateUser(doAddPrePurchBalanceInDTO.getLastUpdaterUser());
       prePurchaseMoneyChange.setOperateUserId(doAddPrePurchBalanceInDTO.getLastUpdaterId());
       prePurchaseMoneyChange.setType(1);//表示渠道调整
     //表示+余额
  	 int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())+prePurchaseMoneyChange.getAmount().intValue();
  	 agent.setPrePurchaseBalance(balance);  
  	 String descMoney=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
  	 agent.setPrePurchaseBalanceDes(descMoney);
  	 
  	 agentMapper.updateByPrimaryKey(agent);
  	 prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
  	 prePurchaseActivity.setStatus(BizEnum.PrePurchaseActivityStatus.endRe.getType());
  	 prePurchaseActivityMapper.updateByPrimaryKey(prePurchaseActivity);
   	baseOutDTO.setErrorCode(Rescode.SUCCESS, "操作成功");
  	 return  baseOutDTO;
	}

	
   
}
